package com.example.demo;

import com.google.gson.Gson;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.NLPTokenizer;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;

/**
 * Created by luke on 18/2/10.
 */
public class FileCooke {

    public static void cooke(String srcPath, String tagPath) {

        FileReader fr = null;
        BufferedReader br = null;

        FileWriter fw = null;
        BufferedWriter bw = null;

        String text = null;
        try {
            fr = new FileReader(srcPath);
            br = new BufferedReader(fr);


            fw = new FileWriter(tagPath);
            bw = new BufferedWriter(fw);

            // 从原文中读出一行
            text = br.readLine();

            Gson gson = new Gson();
            while (text != null){
                // 将原文中的json数据转为bible对象
                BibleWord bible = gson.fromJson(text,BibleWord.class);

                if("箴言".equals(bible.getBook())){
                    // 对经文进行分析
                    List<Term> termList = NLPTokenizer.segment(bible.getMessage());

                    for(Term term : termList){
                        // 过滤标点符号，将除标点符号外的文本存储下来
                        if(!term.nature.startsWith('w')){
                            // 组装要写入到ES里的meta数据
                            bw.write("{ \"index\" : { \"_index\" : \"bible\", \"_type\" : \"zhenyan\"} }\n");
                            // 将添加单词后的对象转换成json字符串，写入文件
                            bible.setWord(term.word);
                            bible.setNature(term.nature.name());
                            bw.write(gson.toJson(bible) + "\n");
//                        bw.newLine();
                        }
                    }
                }

                text = br.readLine();
            }

            br.close();
            fr.close();

            bw.flush();
            bw.close();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String arg[]){

        StopWatch sw = new StopWatch();
        sw.start("cooke bible");

        FileCooke.cooke("/Users/luke/oschina/jieba-demo/json/bible-doc-message.json", "/Users/luke/oschina/jieba-demo/txt/bible-doc-cp");

        sw.stop();
        System.out.println(sw.prettyPrint());
        System.out.println(sw.getTotalTimeMillis());
        System.out.println(sw.getLastTaskName());
        System.out.println(sw.getLastTaskInfo());
        System.out.println(sw.getTaskCount());

    }
}
